<?php

namespace App\Http\Service\frontend;

use App\Common\Utils\Common;
use App\Http\Models\Student\Student;
use App\Http\Models\Student\StudentBuy;
use App\Http\Models\Student\CourseBooking;

class StudentService
{

    public function index($request)
    {
        $studentData = Student::where('open_id', $request->open_id)->first();
        if ($studentData) {
            return [
                'openId' => $request->open_id
            ];
        }
        $data = [
            'nickname'   => $request->nickname,
            'open_id'    => $request->open_id,
            'images'     => $request->images,
            'country'    => $request->country ?? "",
            'province'   => $request->province ?? "",
            'city'       => $request->city ?? "",
            'phone'      => $request->phone ?? 0,
            'sex'        => $request->sex ?? 3,
            'created_at' => time(),
        ];
        if (Student::create($data)) {
            return [
                'openId' => $request->open_id
            ];
        }
        return false;
    }

    public function getUserInfo($openId)
    {
        $studentData = Student::select(['id', 'real_name', 'member_status', 'nickname', 'open_id', 'images', 'phone', 'country', 'province', 'city', 'sex', 'created_at'])->where('open_id', $openId)->first();
        if ($studentData) {
            $where = [
                'student_id' => $studentData->id,
                'stu_status' => 0,
                'status'     => 0,
            ];
            //初始化会员
            $studentBuyVipDataTmp = StudentBuy::getStudentBuyVip($where);
            if ($studentBuyVipDataTmp) {
                if ($studentBuyVipDataTmp->end_time < time()) {
                    $studentData->member_status = 0;
                    $studentData->save();
                }
            }
            //获取团课次数
            $where = [
                'student_id' => $studentData->id,
                'stu_status' => 0
            ];
            //会员时间
            $studentVip = StudentBuy::getStudentBuyVip($where);

            $league_number = 0;
            $leagueNumberDatas = StudentBuy::getStudentBuyAll($where);
            foreach ($leagueNumberDatas as $key => $val) {
//                if ($val['get_user_belongs_to']['end_time'] < time()) {
                if ($val['end_time']) {
                    if ($val['end_time'] < time()) {
                        continue;
                    }
                }

                if (($val['member_number'] - $val['surplus_number']) != 0) {
                    $league_number += ($val['member_number'] - $val['surplus_number']);
                }
//                }
            }
            $where = [
                'student_id' => $studentData->id,
                'stu_status' => 1
            ];
            $educationNumberDatas = StudentBuy::getStudentBuyAll($where);
            $educationNumber = 0;
            if ($educationNumberDatas) {
                foreach ($educationNumberDatas as $key => $val) {
                    if ($val->member_number > $val->surplus_number) {
                        $educationNumber += $val->member_number - $val->surplus_number;
                    }
                }
            }
            $studentData->begin_time = $studentVip ? date("Y-m-d H:i:s", $studentVip->begin_time) : "";
            $studentData->end_time = $studentVip ? date("Y-m-d H:i:s", $studentVip->end_time) : "";
            $studentData->education_number = $educationNumber;
            $studentData->league_number = $league_number;
            $studentData->created_at = date("Y-m-d H:i:s", $studentData->created_at);
            return $studentData;
        }
        return false;
    }

    //用户预约订单
    public function getUserOrder($request)
    {
        $data['list'] = [];
        $page = $request->page ?? FRONTEND_PAGE;
        $limit = $request->limit ?? FRONTEND_LIMIT;
        $studentData = Student::select(['id'])->where('open_id', $request->openId)->first();
        if ($studentData) {
            $query = CourseBooking::with([
                'getUserBelongsTo'   => function ($query) {
                    $query->select(['*']);
                },
                'getDancesBelongsTo' => function ($query) {
                    $query->select(['*']);
                },
            ])->where(['student_id' => $studentData->id])->orderBy('created_at','desc');
            $couresBookingDatas = Common::page($query, $page, $limit);
            foreach ($couresBookingDatas['list'] as $key => $val) {
                $data['list'][$key]['id'] = $val['id'];
                $data['list'][$key]['created_at'] = date('Y-m-d H:i:s', $val['created_at']);
                $data['list'][$key]['teacher_id'] = $val['get_user_belongs_to']['id'];
                $data['list'][$key]['teacher_name'] = $val['get_user_belongs_to']['name'];
                $data['list'][$key]['teacher_phone'] = $val['get_user_belongs_to']['phone'];
                $data['list'][$key]['teacher_images'] = Common::getHost() . $val['get_user_belongs_to']['images'];
                $data['list'][$key]['teacher_level'] = $val['get_user_belongs_to']['level'] ?? "";
                $data['list'][$key]['teacher_synopsis'] = $val['get_user_belongs_to']['synopsis'] ?? "";
                $data['list'][$key]['dances_id'] = $val['get_dances_belongs_to']['id'] ?? "";
                $data['list'][$key]['dances_name'] = $val['get_dances_belongs_to']['name'] ?? "";
                $data['list'][$key]['dance_types'] = DANCE[$val['get_dances_belongs_to']['dance_names']] ?? "";
                $data['list'][$key]['dances_begin_time'] = date('Y-m-d H:i:s', $val['begin_time']) ?? "";
                $data['list'][$key]['dances_end_time'] = date('Y-m-d H:i:s', $val['end_time']) ?? "";
                $data['list'][$key]['dances_address'] = $val['get_dances_belongs_to']['address'] ?? "";
                $data['list'][$key]['dances_contents'] = $val['get_dances_belongs_to']['contents'] ?? "";
                $data['list'][$key]['dances_updated_at'] = $val['get_dances_belongs_to']['updated_at'];
            }
            $data['pageCount'] = $couresBookingDatas['pageCount'];
            $data['totalCount'] = $couresBookingDatas['totalCount'];
        }
        return $data;
    }

    public function getOpenId($request)
    {
        if (isset($request['code'])) {
            $file_contents = file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid=' . APP_ID . '&secret=' . SECRET . '&js_code=' . $request['code'] . '&grant_type=authorization_code');
            return json_decode($file_contents, true);
        }
        return [
            'codes'   => 400,
            'message' => '请输入code',
        ];
    }

    //完善信息
    public function information($request)
    {
        $data = [
            'real_name' => $request->realName,
            'phone'     => $request->phone,
            'country'   => $request->country,
            'province'  => $request->province,
            'city'      => $request->city,
            'sex'       => $request->sex
        ];
        try {
            Student::where('open_id', $request->openId)->update($data);
            return [
                'code'    => 200,
                'message' => INFORMATION_SUCCESS
            ];
        } catch (\Exception $ex) {
            return [
                'code'    => 400,
                'message' => $ex->getMessage()
            ];
        }
    }

}
